package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        if (multipartFile==null&&multipartFile.getSize()<=0){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文件不能为空");

        }
        String original=multipartFile.getOriginalFilename();
        String substring = original.substring(original.lastIndexOf("."));
        if (!checkSuffix(substring)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文件格式不符合要求");

        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"未登录");

        }
        String filename=null;
        try {
            String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + substring;
             filename = fileStorageService.store(prefix, newFileName, multipartFile.getInputStream());
        }catch (IOException e){
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"文件上传OSS失败");
        }
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        // 设置文件id
        wmMaterial.setUrl(filename);
        wmMaterial.setUserId(user.getId());
        this.save(wmMaterial);
        // 前端显示
        wmMaterial.setUrl(webSite+wmMaterial.getUrl());
        // 4 返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        // 1 参数校验
        dto.checkParam();
        // 2 执行业务查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        // 收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        // 当前登录用户的素材
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
             CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wrapper.eq(WmMaterial::getUserId, user.getId());
        // 时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> pageParam = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> resultPage = page(pageParam, wrapper);
        List<WmMaterial> records = resultPage.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }
        // 3 封装结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), resultPage.getTotal());
        pageResponseResult.setData(records);
        return pageResponseResult;

    }
@Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    WmMaterialMapper wmMaterialMapper;
    @Override
    public ResponseResult delPicture(Integer id) {
        if (id==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmMaterial byId = getById(id);
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getMaterialId,id);
        Integer integer = wmNewsMaterialMapper.selectCount(queryWrapper);
        if (integer>0){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"素材被引用，无法删除");
        }
        removeById(id);
        // 删除图片OSS
        fileStorageService.delete(webSite+byId.getUrl());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        WmMaterial material = getById(id);
        if (id==null||material==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"数据不存在");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (!material.getUserId().equals(user.getId())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"只允许收藏自己上传的素材");
        }
        material.setIsCollection(type);
        boolean b = updateById(material);
        if (!b){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"操作失败");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    @Autowired
    FileStorageService fileStorageService;
    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String webSite;

    private boolean checkSuffix(String suffix){
        if (StringUtils.isBlank(suffix)){
            return false;
        }
        List<String> strings = Arrays.asList(".jpg", ".png", ".gif", ".jpeg");
        boolean ischeck=false;
        for (String string :strings){
            if (string.equalsIgnoreCase(suffix)){
                ischeck=true;
                break;
            }
        }
        return ischeck;
    }
}